package com.kanshu.ksgb.fastread.doudou.app;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.location.Location;
import android.os.Build;
import android.support.multidex.MultiDexApplication;
import android.util.Log;

import com.ak.android.charge.ChargeAd;
import com.ak.torch.shell.TorchAd;
import com.alibaba.android.arouter.launcher.ARouter;
import com.github.moduth.blockcanary.BlockCanary;
import com.inmobi.sdk.InMobiSdk;
import com.kanshu.ksgb.fastread.doudou.BuildConfig;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.LifecycleHelper;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideImageLoader;
import com.kanshu.ksgb.fastread.doudou.common.util.CrashHandler;
import com.kanshu.ksgb.fastread.doudou.common.util.LocationUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mmkv.MMKV;
import com.umeng.analytics.MobclickAgent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;
import cn.jpush.android.api.JPushInterface;

public class Xutils extends MultiDexApplication {
    public static Context sContext;
    private static boolean isInit360 = false;
    private static boolean isInitInMobi = false;
    private static Map<String, String> sConfig;
    private static boolean sInitConfig;

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onCreate() {
        super.onCreate();
        init(this);
    }

    public static void initAd(int adType) {
        switch (adType) {
            case ADConfigBean.TYPE_INMOBI:
                if (!isInitInMobi) {
                    InMobiSdk.init(getContext().getApplicationContext(), sContext.getString(R.string.ad_inmobi_account_id));
                    // InMobiSdk.setLogLevel(InMobiSdk.LogLevel.DEBUG);
                    String sex = MMKVUserManager.getInstance().getLoginSex();
                    if (sex.equals(Constants.TYPE_MALE)) {
                        InMobiSdk.setGender(InMobiSdk.Gender.MALE);
                    } else {
                        InMobiSdk.setGender(InMobiSdk.Gender.FEMALE);
                    }
                    Location location = LocationUtils.getLocation(getContext().getApplicationContext());
                    if (location != null) {
                        Log.i("Location", "Latitude:  " + location.getLatitude() + "Longitude: " + location.getLongitude());
                        InMobiSdk.setLocation(location);
                    }
                    isInitInMobi = true;
                }
                break;
            case ADConfigBean.TYPE_360:
                if (!isInit360) {
                    //360初始化
                    TorchAd.initSdk(getContext().getApplicationContext(), false, false);
                    isInit360 = true;
                }
                break;
            default:
                break;
        }
    }

    public static void init360ChargeSDK(String id) {
        ChargeAd.initSdk(getContext().getApplicationContext(), id, false, false);
    }

    private static void jpushInit(Application context) {
        Log.e("test", "start");
        JPushInterface.setDebugMode(false);
        JPushInterface.init(context);
        JPushInterface.getRegistrationID(context);
        // 友盟
        Log.e("test", "umeng");
        MobclickAgent.openActivityDurationTrack(false);
        Log.e("test", "umeng open");
        //捕获程序崩溃日志
        MobclickAgent.setCatchUncaughtExceptions(true);
        Log.e("test", "umeng catch");
        String key = context.getResources().getString(R.string.umeng_app_key);
//        key = "5c11edcbb465f58c5b000205";
        MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(context, key, UserUtils.getOriginChannelId()));
        Log.e("test", "key:" + key + " Origin:" + UserUtils.getOriginChannelId());

    }

    private static void crashHandlerInit(Application context) {
        CrashHandler.getInstance().init(context);
        CrashReport.initCrashReport(context, context.getString(R.string.bugly_app_id), BuildConfig.DEBUG);
    }

    public static Context getContext() {
        return sContext;
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        GlideImageLoader.trimMemory(this, level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        GlideImageLoader.clearMemory(this);
    }

    /**
     * 初始化动作
     *
     * @param context
     */
    public static void init(Application context) {
        if (!Utils.isCurApp(context)) {
            return;
        }
        sContext = context;
        BGASwipeBackHelper.init(context, null);
        // 注册activity生命周期方法
        context.registerActivityLifecycleCallbacks(new LifecycleHandler(new LifecycleHelper()));
        // jpush 初始化
        jpushInit(context);
        // crash采集初始化
        crashHandlerInit(context);
        if (!LeakCanary.isInAnalyzerProcess(context)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            LeakCanary.install(context);
        }
        // 微信mmkv初始化
        MMKV.initialize(context);
        // 阿里路由
        initARouter(context);
        // blockcanary初始化
        // 在主进程初始化调用哈
        // initBlockCanary(context);
    }

    /**
     * router 初始化
     * @param context
     */
    private static void initARouter(Application context) {
        if (BuildConfig.DEBUG) {
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(context);
    }

    private static void initBlockCanary(Application context) {
        if (BuildConfig.DEBUG) {
            // 在主进程初始化调用哈
            BlockCanary.install(context, new AppBlockCanaryContext()).start();
        }
    }

    public static void setContext(Application context) {
        sContext = context;
    }

    /**
     * 从jenkins那儿获取配置
     * @param key
     * @return
     */
    public synchronized static String getServerConfig(String key) {
        if (sContext == null) {
            return "";
        }
        if (sConfig != null && sConfig.size() > 0) {
            return sConfig.get(key);
        } if (sInitConfig) {
            return "";
        }
        InputStream open = null;
        try {
            open = sContext.getAssets().open("config.properties");
            InputStreamReader reader = new InputStreamReader(open);
            BufferedReader reader1 = new BufferedReader(reader);
            String line;
            sConfig = new HashMap<>();
            while ((line = reader1.readLine()) != null) {
                String[] split = line.split("=");
                if (split != null && split.length > 1) {
                    sConfig.put(split[0], split[1]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sInitConfig = true;
            if (open != null) {
                try {
                    open.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (sConfig != null) {
            return sConfig.get(key);
        }
        return "";
    }

}
